<template>
  <div>
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="基础设置" name="A">
      <el-form ref="formEdit" :model="formTemplate" :rules="formRules" size="default" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="模板编码">
              <el-input v-model="formTemplate.templateCode" placeholder="请输入模板编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模板名称">
              <el-input v-model="formTemplate.templateName" placeholder="请输入模板名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模板标题">
              <el-input v-model="formTemplate.templateTitle" placeholder="请输入模板标题"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模板类型">
              <el-select v-model="formTemplate.templateType" style="width: 100%;" class="m-2" placeholder="请输入模板类型">
                <el-option
                  v-for="item in templatetype"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属分类" prop="categoryID">
              <el-cascader
                :options="menuOptions"
                :props="{ label: 'title',value: 'id',checkStrictly: true,emitPath: false }"
                placeholder="选择上级分类"
                clearable
                class="w100"
                v-model="formTemplate.categoryID"
              >
                <template #default="{ node, data }">
                  <span>{{ data.title }}</span>
                  <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="启用">
              <el-switch
                v-model="formTemplate.iSActive"
                inline-prompt
                :active-value="1"
                :inactive-value="0"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="启用审核">
              <el-select v-model="formTemplate.allowBestFitColumns" placeholder="审核">
                <el-option
                    v-for="item in auditoptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="启用复制">
              <el-switch
                v-model="formTemplate.allowCooperate"
                inline-prompt
                :active-value="1"
                :inactive-value="0"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="启用表单布局">
              <el-switch
                  v-model="formTemplate.allowPcDisp"
                  inline-prompt
                  :active-value="1"
                  :inactive-value="0"
                  active-text="是"
                  inactive-text="否"
              />
            </el-form-item>
          </el-col>
            <el-col :span="3" v-if="formTemplate.templateType===1" >
                <el-form-item label="结束节点">
                    <el-input v-model="formTemplate.endFlowCode" placeholder="请输入结束节点标记"/>
                </el-form-item>
            </el-col>
            <el-col :span="3">
                <el-form-item label="启用默认打印">
                    <el-switch
                            v-model="formTemplate.allowPrintWith"
                            inline-prompt
                            :active-value="1"
                            :inactive-value="0"
                            active-text="是"
                            inactive-text="否"
                    />
                </el-form-item>
            </el-col>
          <el-col :span="3" v-if="formTemplate.templateType===4" >
            <el-form-item label="数据模板">
              <el-input v-model="formTemplate.enterDirect" placeholder="请输入动态数据来源模板编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="formTemplate.memo" placeholder="请输入备注"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="加载过滤">
              <el-input v-model="formTemplate.loadFilter" placeholder="如需要请请输入"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" @click="submitEvent1(formEdit)">保存</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </el-tab-pane>
      <el-tab-pane label="数据表字段" name="B">
          <vxe-table
            border
            size="small"
            :align="allAlign"
            ref="Table" keep-source
            height="300"
            :edit-config="{trigger: 'click', mode: 'cell', showStatus: true}"
            :row-config="{isCurrent: true, isHover: true}"
            @cell-click="tableClick"
            :edit-rules="rules.table"
            :checkbox-config="{labelField: 'tableID', highlight: true, range: true}"
            :data="tableData"
          >
            <vxe-column type="seq" width="60"></vxe-column>
            <vxe-column type="checkbox" field="tableID" title="ID" width="100"></vxe-column>
            <vxe-column field="tableName" title="后台表" width="100"></vxe-column>
            <vxe-column field="tableDispName" title="表名称"  min-width="160" :edit-render="{name: 'input', attrs: {type: 'text'}}">
              <template #edit="{ row }">
                <vxe-input v-model="row.tableDispName" placeholder="请输入..." @blur="()=>{if(row.tableTitle===''){row.tableTitle=row.tableDispName}}"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="tableTitle" title="表标题" min-width="160"  :edit-render="{name: 'input', attrs: {type: 'text'}}"></vxe-column>
            <vxe-column field="tableType" title="表类型" width="120" :edit-render="{name: '$select', options:tableType }"></vxe-column>
            <vxe-column field="created" title="建表方式" width="120" :formatter="formatterCreated" :edit-render="{name: '$select', options:tableCreated ,events:{change:chosetableEvents}}"></vxe-column>
            <vxe-column field="hidden" title="隐藏" width="80" :cell-render="{name: '$switch', props:{openLabel:'是',openValue:1,closeLabel:'否',closeValue:0}}"></vxe-column>
            <vxe-column field="autoIncrement" title="自增ID" width="80" :cell-render="{name: '$switch', props:{openLabel:'是',openValue:1,closeLabel:'否',closeValue:0}}"></vxe-column>
            <vxe-column field="onSheet" title="合计字段" width="160" :cell-render="{name: 'input', attrs: {type: 'text'}}"></vxe-column>
            <vxe-column field="layoutStyle" title="树形字段" width="160" :cell-render="{name: 'input', attrs: {type: 'text'}}"></vxe-column>
            <vxe-column field="excelFormulaAutoFill" title="表格高度" width="160" :cell-render="{name: 'input', attrs: {type: 'text'}}"></vxe-column>
<!--            <vxe-column field="allowWorkFlow" title="取数后是否取默认值" width="160"  :cell-render="{name: '$switch', props:{openLabel:'是',openValue:1,closeLabel:'否',closeValue:0}}"></vxe-column>-->
          </vxe-table>
          <vxe-toolbar
            ref="xToolbar2"
            :buttons="toolbarButtons"
            @button-click="buttonsClick"
          >
           </vxe-toolbar>
          <vxe-table
            border
            size="mini" keep-source
            :align="allAlign"
            ref="Field" height="500"
            :edit-rules="rules.fields"
            :edit-config="{trigger: 'click', mode: 'cell', showStatus: true,icon: ''}"
            :row-config="{isCurrent: true, isHover: true}"
            :checkbox-config="{labelField: 'fieldID', highlight: true, range: true}"
            :data="fieldData"
          >
            <vxe-column type="seq" width="40" fixed="left"></vxe-column>
            <vxe-column type="checkbox" fixed="left" field="fieldID" title="ID" width="70"></vxe-column>
            <vxe-column field="tableID" :visible="false" :filters="[{ data: '' }]" title="表ID"></vxe-column>
            <vxe-column field="fieldName" fixed="left" title="后台字段" width="80"></vxe-column>
            <vxe-column field="fieldDispName" fixed="left" title="字段名称" width="100" show-overflow :edit-render="{name: 'input',props:{type:'text'}, autoselect: true }">
              <template #edit="{ row }">
                <vxe-input v-model="row.fieldDispName" placeholder="请输入..." @blur="row.fieldTitle=row.fieldDispName"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="fieldTitle" title="字段标题" width="100" show-overflow :edit-render="{name: 'input', props:{type:'text'}, autoselect: true}"></vxe-column>
            <vxe-column field="dataTypeID" title="类型" width="62" :edit-render="{name:'$select', options:dataType,events:{change:changeDataType}}"></vxe-column>
            <vxe-column field="fieldLength" title="长度" width="62" :edit-render="{name: '$input',props:{type:'integer',min:1 }, autoselect: true }"></vxe-column>
            <vxe-column field="fieldPrecision" title="小数" width="62" :edit-render="{name: '$input',props:{type:'integer'} }"></vxe-column>
            <vxe-column field="primaryKey" title="主键" width="62" :cell-render="{name: '$switch', props:{openLabel:'是',openValue:1,closeLabel:'否',closeValue:0}}"></vxe-column>
            <vxe-column field="nullable" title="必填" width="62" :cell-render="{name: '$switch', props:{openLabel:'是',openValue:1,closeLabel:'否',closeValue:0}}"></vxe-column>
            <vxe-column field="editable" title="编辑" width="62" :cell-render="{name: '$switch', props:{openLabel:'是',openValue:1,closeLabel:'否',closeValue:0}}"></vxe-column>
            <vxe-column field="hidden" title="隐藏" width="62" :cell-render="{name: '$switch', props:{openLabel:'是',openValue:1,closeLabel:'否',closeValue:0}}"></vxe-column>
            <vxe-column field="nullToField" title="不打印" width="62" :cell-render="{name: '$switch', props:{openLabel:'是',openValue:1,closeLabel:'否',closeValue:0}}"></vxe-column>
            <vxe-column field="allowFixedWidth" title="宽度" width="62" :edit-render="{name: '$input',props:{type:'integer',min:1 }, autoselect: true }"></vxe-column>
            <vxe-column field="fieldAreaName" title="查询类型" width="100" :cell-render="{name: '$select', options:searchType}"></vxe-column>
            <vxe-column field="default" title="默认值" width="130" show-overflow :edit-render="{ }">
              <template #default="{ row }">{{ row.default }}</template>
              <template #edit="{ row }">
                <vxe-pulldown transfer ref="xxxx">
                  <template #default>
                    <vxe-input v-model="row.default" placeholder="" class="my-search" @suffix-click="showpull(row)">
                      <template #suffix>
                        <el-icon>
                          <Plus/>
                        </el-icon>
                      </template>
                    </vxe-input>
                  </template>
                  <template #dropdown>
                    <div class="my-dropdown4">
                      <vxe-table
                          border
                        auto-resize
                        :show-header="false"
                        height="auto"
                        :row-config="{isHover: true}"
                        :data="defaults"
                        @cell-click="clickdefault"
                      >
                        <vxe-column field="componentName" title="默认值"></vxe-column>
                      </vxe-table>
                    </div>
                  </template>
                </vxe-pulldown>
              </template>
            </vxe-column>
            <vxe-column field="dispSeq" title="顺序" width="62" :edit-render="{name: 'input',props:{type:'integer'}, autoselect: true }"></vxe-column>
            <vxe-column field="orderBy"  title="字段排序" width="85" :cell-render="{name: '$select', options:[{ label: '无排序', value: 0 },{ label: '正序', value: 1 },{ label: '倒序', value: 2 }]}"></vxe-column>
            <vxe-column field="componentFieldID" title="数据规范" width="160" :formatter="({row})=>{return row.componentFieldID}" :edit-render="{name: '$input',props:{suffixIcon:'el-icon-more',readonly:true,placeholder:'点击选择...'} ,events:{searchClick:()=>{console.log('ok')},click:showDataGridGuid}}"></vxe-column>
            <vxe-column field="componentFilterExpr" title="过滤" width="62" show-overflow></vxe-column>
            <vxe-column field="componentFieldName" title="填充" width="62" show-overflow></vxe-column>
            <vxe-column field="nullAlertMsg" title="空值提醒" width="90" :edit-render="{name: 'input', }"></vxe-column>
            <vxe-column field="expandType" title="扩展属性" show-overflow width="90" :edit-render="{name: 'input', }"></vxe-column>
            <vxe-column field="regexExpr" title="正则匹配"  show-overflow width="90" :edit-render="{name: 'input', }"></vxe-column>
            <vxe-column field="regexAlertMsg" title="正则提醒"  show-overflow width="90" :edit-render="{name: 'input', }"></vxe-column>
            <vxe-column field="reportSet" title="报表字段设置" width="150" :formatter="({row})=>{return row.reportSet!==null&&row.reportSet!==undefined &&row.reportSet.length>0?'查看数据': ''}" :edit-render="{name: '$input',props:{readonly:true,placeholder:'点击设置...'} ,events:{searchClick:()=>{console.log('ok')},click:showReportSetForm}}"></vxe-column>
          </vxe-table>
    </el-tab-pane>
      <el-tab-pane label="数据公式" name="G">
      <div >
        <datarule :Template="selectTemplate" :Fields="rullfield" :DataSource="DataSource" :load="mulaload" v-on:close="closeDatarule"></datarule>
      </div>
    </el-tab-pane>
     <el-tab-pane v-if="formTemplate.allowPcDisp===1" label="表单布局设置" name="E">
       <div>
         <!-- <formdesign @supform="supform" :data="tableData"></formdesign> -->
         <formCss :data="formTemplate" :tableData="tableData" @saveformCss="saveformCss"></formCss>
       </div>
   </el-tab-pane>
  <el-tab-pane label="打印设置" name="C">
   <div>
     <print v-if="activeName==='C'" :sid="formTemplate.templateID" :tableData="tableData"></print>
   </div>

 </el-tab-pane>
 <!-- <el-tab-pane label="打印设置2" name="tt">
  <printZ :tableData="tableData" :sid="formTemplate.templateID"></printZ>
 </el-tab-pane> -->
        <el-tab-pane label="流程设计" name="D" v-if="formTemplate.allowBestFitColumns===5">
            <div style="height:calc(100vh - 150px);">
                <ProcessdesignH  :title="formTemplate.templateName+'审批流程'" :templateInfos="templateInfos" ></ProcessdesignH>
            </div>
        </el-tab-pane>
        <el-tab-pane label="流程设计" name="D" v-if="formTemplate.allowBestFitColumns===2">
            <div style="height:calc(100vh - 150px);">
                <Processdesign :title="formTemplate.templateName+'审批流程'" :process="formTemplate.Process" :tabDatasxm="tableData" @flowsave="flowsave" :load="loadproc" :templateID="formTemplate.templateID"></Processdesign>

            </div>
        </el-tab-pane>
      <el-tab-pane label="外部流程关联"  v-if="formTemplate.allowBestFitColumns===3"  name="outFlow">
        <div>
          <associated :TF="tableData" :data="extFlow" @saveExtFlow="saveExtFlow"></associated>
        </div>
      </el-tab-pane>

  </el-tabs>
    <vxe-modal v-model="showTableChose" ref="TableChose" width="800" height="600" title="映射表选择" destroy-on-close show-zoom resize>
      <template #default>
        <el-row>
          <el-col :span="11">
            <vxe-table
              border
              auto-resize
              show-overflow
              ref="choseTable"
              size="mini"
              height="500"
              width="100%"
              :tree-config="{}"
              :row-config="{isCurrent: true, isHover: true}"
              :data="chosetable.tableData"
              @cell-click="chosetableClickEvent"
            >
              <vxe-column field="name" title="后台名称" width="100" tree-node></vxe-column>
              <vxe-column field="title" title="模板表称"></vxe-column>
            </vxe-table>
          </el-col>
          <el-col :span="13">
            <vxe-table
              border
              auto-resize
              ref="choseTableFields"
              size="mini"
              height="500"
              width="100%"
              :row-config="{isHover: true}"
              :checkbox-config="{labelField: 'fieldName'}"
              :data="chosetable.fieldData"
            >
              <vxe-column type="seq" width="60"></vxe-column>
              <vxe-column type="checkbox" title="后台名称" width="100"></vxe-column>
              <vxe-column field="fieldDispName" title="字段名称"></vxe-column>
            </vxe-table>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center">
          <el-button type="primary" @click="buildTF">确定</el-button>
        </el-row>
      </template>
    </vxe-modal>
    <vxe-modal v-model="showDataGrid" ref="DataGrid" width="70%" height="80%" destroy-on-close show-zoom resize remember :showHeader="false">
      <template #default>
        <specification :TFData="toDataGridTables" :FillData="FillData" :FieldRow="selectDSRow" v-on:submitew="getFieldDataGrid"></specification>
      </template>
    </vxe-modal>
    <vxe-modal v-model="showReportSet" ref="ReportSet" width="600" height="600" title="报表字段设置" destroy-on-close show-zoom resize  show-footer>
      <template #default>
        <vxe-form :data="ReportSetForm" ref="ReportSettForm" title-align="right" title-width="100" >
          <vxe-form-item field="fieldType" title="数据类型" :span="24" :item-render="{}">
            <template #default="{data}">
              <vxe-radio-group v-model="ReportSetForm.fieldType">
                <vxe-radio-button label="title" content="表头字段"></vxe-radio-button>
                <vxe-radio-button label="data" content="数据字段"></vxe-radio-button>
              </vxe-radio-group>
            </template>
          </vxe-form-item>
          <vxe-form-item  field="titleLevel" title="表头级别" :span="24" :item-render="{}" :visible-method="({ data }) =>ReportSetForm.fieldType==='title'">
            <template  #default="{data}" >
              <vxe-radio-group v-model="data.titleLevel">
                <vxe-radio-button label="1" content="一级表头"></vxe-radio-button>
                <vxe-radio-button label="2" content="二级表头"></vxe-radio-button>
                <vxe-radio-button label="3" content="三级表头"></vxe-radio-button>
              </vxe-radio-group>
            </template>
          </vxe-form-item>
          <vxe-form-item field="titlePrefix" title="表头前缀" :span="24" :item-render="{name:'input'}"  :visible-method="({ data }) =>ReportSetForm.fieldType==='title'"></vxe-form-item>
          <vxe-form-item field="titleSuffix" title="表头后缀" :span="24" :item-render="{name:'input'}"  :visible-method="({ data }) =>ReportSetForm.fieldType==='title'"></vxe-form-item>
          <vxe-form-item field="dataField" title="数据字段" :span="24" :item-render="{name:'input'}"  :visible-method="({ data }) =>ReportSetForm.fieldType==='title'"></vxe-form-item>
          <vxe-form-item field="dataSet" title="数据字段设置" :span="24" :item-render="{}" :visible-method="({ data }) =>ReportSetForm.fieldType==='data'">
            <template #default="{ data }">
              <vxe-checkbox-group v-model="data.dataSet">
                <vxe-checkbox label="sum" content="合计"></vxe-checkbox>
              </vxe-checkbox-group>
            </template>
          </vxe-form-item>
          <vxe-form-item field="dataWithField" title="数据只显示在某个字段" :span="24" :item-render="{name:'input'}" :visible="ReportSetForm.fieldType==='data'">
          </vxe-form-item>

        </vxe-form>
      </template>
      <template #footer>
        <vxe-button status="primary" @click="submitEventReportSetForm">提交</vxe-button>
        <vxe-button @click="ReportSettForm.reset()">重置</vxe-button>
      </template>
    </vxe-modal>
  </div>
</template>
<script>
import {
  addTemplate,
  buildWithDing,
  editTemplateTable,
  getDatasource,
  getTemplateInfo,
  getSetTemplateInfo,
  listDatatype,
  rebuildTemplatetable,
  updateTemplate
} from "/@/api/linkoo/templates";
import {listCateMenu} from "/@/api/linkoo/category"
import formCss from "./components/formcss/index.vue"
import {defineComponent, onBeforeMount, reactive, ref, toRefs, watch} from 'vue'
import {listDatagrid} from "/@/api/linkoo/datagrid"
import {handleTree} from "/@/utils/ruoyi"
import {ElMessage, ElMessageBox} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import {useRoute, useRouter} from 'vue-router';
import ProcessdesignH from "./components/processdesign/index.vue"
import Processdesign from "./Processdesign.vue"
import XEUtils from 'xe-utils'
import formdesign from "./formdesign.vue"
import associated from '/@/views/linkoo/components/associated.vue'
import specification from './components/specification.vue'
import datarule from "./components/formula/index.vue"
import print from "./components/print/print.vue"
import printZ from "../print/print3.vue"
import sxForm from "../../linkoo/components/sxForm.vue"
export default defineComponent({
  name: 'templatesEdit',
  components: {print,ProcessdesignH, Processdesign,printZ,formdesign, associated, specification, datarule,formCss,sxForm},
  setup() {
    let Table = ref(null)
    let Field = ref(null)
    let ReportSettForm = ref(null)
    const formEdit = ref(null)
    const auditoptions =  ref([{value: 0,label: '不启用',},{value: 1,label: '直接审核',},{value: 2,label: '内部流程',disabled: true,},{value: 3,label: '外部流程',},{value: 5,label: '高级流程',}])
    const state = reactive({
      showTableChose: false,
      loadproc: false,
      selectRow: "",
      ReportSetForm: {fieldType: null, titleLevel: null, dataSet: null,},
      DingFroms: {},
      defaultrow: {},
      toDataGridTables: [],
      loading:false,
      defaults: [],
      datagridList: [],
      allAlign: null,
      showTableEdit:false,
      submitLoading:false,
      EditedRow: [],
      DataSource: [],
      templateTableData:[],
      formRules: { categoryID: [{ required: true, message: '必填填写', trigger: 'blur' }] },
      activeName : 'A',
      menuOptions: [],
      templatetype: [{ label: '表单', value: 1 }, { label: '报表', value: 2 }, { label: '直改表', value: 3 }, { label: '动态表', value:4 }],
      tempTableId: 0,
      tempFieldId: 0,
      selectTable: null,
      FillData: [],
      showReportSet: false,
      showDataGrid: false,
      mulaload: false,
      selectTemplate: null,
      extFlow: null,
      rullfield: [],
      formTemplate: {templateID:0,templateName:'',allowBestFitColumns:0,allowPcDisp:0},
      tableData:[],
      tonumbers: ['fieldLength', 'fieldPrecision',  'orderby','allowFixedWidth','dispSeq','excelFormulaAutoFill'],
      fieldData: [],
      dataType: [],
      searchType:[{value: '', label: '不查询'}, {value: '=', label: '等于'}, {value: '<>', label: '不等于'},
        {value: '<',label: '小于'}, {value: '<=', label: '小于等于'}, {value: '>', label: '大于'}, {value: '>=', label: '大于等于'},
        {value: 'like',label: '包含'      }, {value: 'in', label: '在列表中'}, {value: 'between', label: '区间'}],
      selectDSRow: {},
      ystable:{},
      rules: {
        table: { 'tableDispName': [{ 'message': '表名称必须填写!', 'required': true }] },
        fields: { 'fieldDispName': [{ 'message': '字段名称必须填写!', 'required': true }] }
      },
      tableCreated: [{ label: '普通表', value: 1 }, { label: '映射表', value: 2 }, { label: '临时表', value: 3 }, { label: '主列表', value: 4 }],
      chosetable: {
        tableData: [],
        fieldData: []
      },
        templateInfos:{},
      toolbarButtons: [
        { code: 'tableAdd', name: '新增表' },
        {
          name: '表其它按钮',
          dropdowns: [
            { name: '删除选中表', code: 'tableDelete' },
            { name: '重建选中表', code: 'rebuildTable' },
            { name: '从钉钉表单创建', code: 'buildWithDing' }
          ]
        },
        { code: 'fieldAdd', name: '新增字段' },
        {
          name: '字段其它按钮',
          dropdowns: [
            { name: '删除选中字段', code: 'fieldDelete' }
          ]
        },
        {code: 'SaveTable', name: '保存', status: 'success'},
        {code: 'Cancel', name: '取消', status: 'primary'}
      ],
      tableType: [{label: '主表', value: 0}, {label: '明细表', value: 1}],
    });
    const handleClick = (tab, event) => {
     // console.log(tab, event)
    };
    // watch(() => state.ReportSetForm.fieldType,(newValue,oldValue)=>{
    //   console.log('变化后的值是'+newValue, '变化前的值是'+oldValue);
    // },{ deep: true })
    const route = useRoute();
    const templateInfo =  () => {
      state.fieldData = []
      getSetTemplateInfo(route.params['templateCode']).then(res => {
          state.templateInfos=res.data
        state.formTemplate = res.data.template
        state.formTemplate.Process=XEUtils.toStringJSON(state.formTemplate.Process)
        state.extFlow = XEUtils.toStringJSON(res.data.template.badgeExpr)
        state.tableData = res.data.tables||[]
        setTimeout(()=>{
          if (!state.selectTable){
            const $table = Table.value
            $table.setCurrentRow(state.tableData[0])
            tableClick({row:state.tableData[0]})
          }
        },500)
        XEUtils.arrayEach(res.data.tables, row => {
          state.fieldData = state.fieldData.concat(row.Fields || [])
        })
        state.selectTemplate = res.data.template
        let TB = {}, FD = {}
        state.tableData.forEach(row => {
          TB[row['tableID']] = row['tableName']
            FD[row['tableName']] = row
            FD[row['tableName']]['Children'] = []
          })
        state.fieldData.forEach(field => {
          if(field.dispSeq===0){
            field.dispSeq=null
          }
          if(field.allowFixedWidth===0){
            field.allowFixedWidth=null
          }
          FD[TB[field.tableID]]['Children'].push(field)
        })
        state.rullfield = state.tableData
        getDatasource().then(res=>{
          state.DataSource =res.data.list
          state.mulaload=true
        })

      })
      state.loadproc=true
    };
    onBeforeMount(async ()=>{
       listCateMenu("").then(response => {
         const menu = { id: 0, title: '主类目', 'children':[]};
         menu.children = handleTree(response.data.list, "id", "pid", "children", 0);
         state.menuOptions.push(menu);
       })
      getComponentTypes()
      getDataTypes()
      if (route.params['templateCode'] === '_addNewTemplate_') {
        return
      }
     await  templateInfo()
    });
    const getDataTypes = () => {
      listDatatype().then(res => {
        let items = []
        res.data.list.forEach(row => {
          items.push(XEUtils.assign({label: row.dataTypeName, value: row.dataTypeID}, row))
        })
        state.dataType = items
      })
    }
    const tableClick = ({row}) => {
      state.selectTable = row
      const xTable = Field.value
      const column = xTable.getColumnByField('tableID')
      xTable.setFilter(column, [{value: row.tableID, checked: true}])
      xTable.updateData()
    }
    const chosetableEvents = () => {
     const row= state.selectTable
      if (row.created === 2) {
        state.showTableChose = true
        if (state.chosetable.tableData.length === 0) {
          state.chosetable.tableData = XEUtils.clone(state.DataSource.find(item=>item.id===1).children,true)
        }
      }
    }
    const formatterCreated=({ cellValue })=>{
      const lb = state.tableCreated.find(item => item.value === cellValue)
      return lb === undefined ? cellValue : lb['label']
    }
    const buttonsClick= async ({ code, button, $event })=>{
      const $table = Table.value
      const $field = Field.value
      switch (code) {
        case 'tableAdd':
          const tt = XEUtils.map($table.getTableData().tableData, item => item.tableType)

          const trecord = {
            tableID: state.tempTableId++,
            tableName: '系统生成',
            created: 1,
            templateID: state.formTemplate.templateID,
            tableDispName: state.formTemplate.templateName + '_' + (XEUtils.includes(tt, 0) ? '明细表' + (XEUtils.sum(tt) ? XEUtils.sum(tt).toString() : '') : '主表'),
            tableTitle: state.formTemplate.templateName + '_' + (XEUtils.includes(tt, 0) ? '明细表' + (XEUtils.sum(tt) ? XEUtils.sum(tt).toString() : '') : '主表'),
            tableType: XEUtils.includes(tt, 0) ? 1 : 0,
            hidden: 0
          }

          const { row: tnewRow } = await $table.insertAt(trecord, -1)
          await $table.setActiveCell(tnewRow, 'tableDispName')
          await $table.setCurrentRow(tnewRow)
          tableClick({ row: tnewRow })
          state.tempTableId++
          break
        case 'fieldAdd':
          if( $table.getCurrentRecord()===null){
            ElMessage.error( '选择数据后再操作!')
            return
          }
          const frecord = {
            tableID: state.selectTable.tableID,
            fieldName: '系统生成',
            fieldDispName: '字段' + state.tempFieldId,
            fieldTitle: '字段' + state.tempFieldId,
            dataTypeID: 1,
            fieldLength: 120,
            fieldID: state.tempFieldId,
            fieldPrecision: 0,
            primaryKey: 0,
            nullable: 0,
            editable: 1,
            hidden: 0,
            default: '',
            orderby: 0,
            dispSeq: null,
            componentType: 0,
            componentID: 0

          }
          const { row: fnewRow } = await $field.insertAt(frecord, -1)
          await $field.setActiveCell(fnewRow, 'fieldDispName')
          await $field.setCurrentRow(fnewRow)
          state.tempFieldId++
          break
        case 'tableDelete':
          const rows = $table.getCheckboxRecords()
          if (rows.length > 0) {
            ElMessageBox.confirm(
              '您确定要删除该数据?',
            '警告',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
          ).then(()=>{
            rows.forEach(function(item) {
                $field.remove($field.getTableData().tableData.filter(items => items.tableID === item.tableID))
              })
              $table.remove(rows)
          })
          } else {
            ElMessage({
                  type: 'error',
                  message: '选择数据后再删除!',
            })
          }
          break
        case 'rebuildTable':
          const table = $table.getCheckboxRecords()
          if (table.length > 0) {
            let t = table[0]
            ElMessageBox.confirm(
              '您确定要重建[' + t.tableDispName + ']?',
            '警告',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
          ).then(()=>{
            rebuildTemplatetable(t.tableID).then(res => {
                if (res.code === 0) {
                  ElMessage({
                        type: 'success',
                        message: '重建表成功',
                  })
                } else {
                  ElMessage({
                      type: 'error',
                      message: res.msg,
                })
                }
              })
          })
          } else {
            ElMessage({
                      type: 'error',
                      message: '选择表后再操作!',
                })
          }
          break
        case 'fieldDelete':
          const Fieldrows = $field.getCheckboxRecords()
          if (Fieldrows.length > 0) {
            ElMessageBox.confirm(
                '您确定要删除该数据?',
                '警告',
                {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning',
                }
            ).then(() => {
              $field.remove(Fieldrows)
            })
          } else {
            ElMessage({
              type: 'error',
              message: '选择数据后再删除!',
            })
          }

          break
        case 'SaveTable':
          const errMap = await $table.fullValidate().catch(errMap => errMap)
          if (errMap) {
            let msgList = []
            Object.values(errMap).forEach(errList => {
              errList.forEach(params => {
                let { row, column, rules } = params
                rules.forEach(rule => {
                  msgList.push(`表ID为 ${row.tableID} 的行中 ${column.title} 校验错误：${rule.message}`)
                })
              })
            })
            ElMessage({
                  type: 'error',
                  message: msgList.join('\n'),
            })
          } else {
            const errfield = await $field.fullValidate().catch(errMap => errMap)
            if (errfield) {
              let msgList = []
              Object.values(errfield).forEach(errList => {
                errList.forEach(params => {
                  let { row, column, rules } = params
                  rules.forEach(rule => {
                    msgList.push(`字段ID为 ${row.fieldID} 的行中 ${column.title} 校验错误：${rule.message}`)
                  })
                })
              })
              ElMessage({
                  type: 'error',
                  message: msgList.join('\n'),
            })
            } else {
              let sendData = {}, iferr = false, errmsg = ''
              sendData['TD'] = XEUtils.orderBy(Table.value.getRemoveRecords(), '_X_ROW_KEY') //删除数据
              sendData['FD'] = XEUtils.orderBy(Field.value.getRemoveRecords(), '_X_ROW_KEY')//删除数据
              sendData['TE'] = XEUtils.orderBy(Table.value.getUpdateRecords(), '_X_ROW_KEY').map(row => {
                return toNumbers(row)
              })//修改数据
              sendData['FE'] = XEUtils.orderBy(Field.value.getUpdateRecords(), '_X_ROW_KEY').map(row => {
                return toNumbers(row)
              })//修改数据
              sendData['TA'] = XEUtils.orderBy(Table.value.getInsertRecords(), '_X_ROW_KEY').map(row => {
                return toNumbers(row)
              })//新增数据
              sendData['FA'] = XEUtils.orderBy(Field.value.getInsertRecords(), '_X_ROW_KEY').map(row => {
                return toNumbers(row)
              })//新增数据
              // if(this.EditedRow.length>0){
              //   sendData['FE']= sendData['FE'].concat(this.EditedRow)
              //   this.EditedRow=[]
              // }
              XEUtils.arrayEach(sendData['TA'], (item, key) => {
                if (sendData['FA'].filter(items => items.tableID === item.tableID).length < 1) {
                  iferr = true
                  errmsg = '表[' + item.tableDispName + ']中没有字段数据,无法新增!修改好再重试'
                }
              })
              if (iferr) {
                ElMessage({
                  type: 'error',
                  message: errmsg,
            })
                return
              }
              editTemplateTable(sendData).then(response => {
                if (response.code === 0) {
                  ElMessage({
                        type: 'success',
                        message: '修改成功',
                  })
                  templateInfo()
                } else {
                  ElMessage({
                  type: 'error',
                  message: response.msg,
            })
                }
              })
            }
          }
          break
        case 'Cancel':
          state.showTableEdit = false
          break
        case 'buildWithDing':
          buildWithDing(state.selectTemplate.dingProcID).then(res => {
            console.log(res)
          })
          break

      }
    }
    const showReportSetForm =({row})=>{
      state.selectDSRow = row
      state.ReportSetForm=XEUtils.toStringJSON(row['reportSet'])
      state.showReportSet=true
    }
    const showDataGridGuid =({row})=>{
      state.selectDSRow = row
        console.log(row)
      getTableTree()
      state.FillData = Field.value.getTableData().visibleData
      state.showDataGrid = true
    }
    const getTableTree=()=> {
      state.toDataGridTables = []
      state.tableData.forEach(row => {
        let fields = state.fieldData.filter(item => item.tableID === row.tableID)
        row[`children`] = fields
        state.toDataGridTables.push(row)
      })
    }
    const changeDataType =({row})=>{
      const kk = state.dataType.find(item => item.dataTypeID === row.dataTypeID)
      row.fieldLength = kk.baseLength
      row.fieldPrecision = kk.basePrecision
    }
    const normalizer=(node) =>{
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.title,
        children: node.children
      }
    }
    let router = useRouter()
    const submitEvent1 = async (formEl) => {
      if (!formEl) return
      await formEl.validate((valid, fields) => {
        if (valid) {
          if (state.formTemplate.templateID !== 0) {
            updateTemplate(state.formTemplate).then(response => {
              if (response.code === 0) {
                ElMessage({
                  type: 'success',
                  message: `修改成功`,
                })
              } else {
                ElMessage({
                  type: 'error',
                  message: response.msg,
                })
              }
            })
          } else {
            addTemplate(state.formTemplate).then(response => {
              if (response.code === 0) {
                ElMessage({
                  type: 'success',
                  message: `新增成功`,
                })
                router.push({path: '/templates/edit/'+state.formTemplate.templateCode})
              } else {
                ElMessage({
                  type: 'error',
                  message: response.msg,
                })
              }
            })
          }
        } else {
          console.log('失败', fields)
          ElMessage({
            type: 'error',
            message: "完善必填项！！",
          })
        }
      })
    }
    const toNumbers=(row)=> {
      XEUtils.objectEach(row, (item, key) => {
        if (XEUtils.includes(state.tonumbers, key)) {
          row[key] = XEUtils.toNumber(item)
        }
      })
      return row
    }
    const getTables=(id)=>{

    }
    let choseTable = ref(null)
    let choseTableFields =ref(null)
    const buildTF= async() =>{
      const $table = Table.value
      const $field = Field.value
      const tableRow = XEUtils.clone(state.ystable,true)
      const fields = choseTableFields.value.getCheckboxRecords()
      const table = $table.getCurrentRecord()
      table.created = 2
      table.tableName = tableRow.tableName
      // table.tableDispName = tableRow.tableDispName
      // table.tableTitle = tableRow.tableTitle
      for (let i = 0; i < fields.length; i++) {
        const frecord = fields[i]
        frecord.tableID = state.selectTable.tableID
        frecord.fieldID = state.tempFieldId
        await $field.insertAt(frecord, -1)
        state.tempFieldId++
      }
      state.showTableChose = false
    }
    const chosetableClickEvent=({ row }) =>{
      state.ystable=row
      state.chosetable.fieldData = row.Fields
    }
    const DataGrid=ref(null)
    const getFieldDataGrid =({ data, status })=>{
      if ((status === 2 || status === 0)) {
        XEUtils.objectEach(data, (item, key) => {
          state.selectDSRow[key] = item
        })
        state.EditedRow.push(state.selectDSRow)
      }
      DataGrid.value.close()
    }
    const submitEventReportSetForm=()=>{
      const da=XEUtils.toJSONString(state.ReportSetForm)
      state.selectDSRow['reportSet'] = da
      state.showReportSet=false
    }
    let xxxx = ref(null)
    const showpull=(row) =>{
      state.defaultrow = row
      xxxx.value.showPanel()
    }
    const getComponentTypes = ()=>{
      listDatagrid().then(response => {
        state.datagridList = response.data.list
        state.defaults = response.data.default
      })
    }
    const clickdefault=({ row }) =>{
      state.defaultrow.default = row.componentName
      xxxx.value.hidePanel()
    }
    const closeDatarule = ()=>{

    }
    const supform = (data)=>{
      state.formTemplate.FormCode=data
      console.log(state.formTemplate);
      if (state.formTemplate.templateID !== 0) {
            updateTemplate(state.formTemplate).then(response => {
              if (response.code === 0) {
                ElMessage({
                  type: 'success',
                  message: `修改成功`,
                })
              } else {
                ElMessage({
                  type: 'error',
                  message: response.msg,
                })
              }
            })
          } else {
            addTemplate(state.formTemplate).then(response => {
              if (response.code === 0) {
                ElMessage({
                  type: 'success',
                  message: `新增成功`,
                })
                router.push({path: '/templates/edit/'+state.formTemplate.templateCode})
              } else {
                ElMessage({
                  type: 'error',
                  message: response.msg,
                })
              }
            })
          }
    }
    const saveExtFlow= (data)=>{
      state.formTemplate.badgeExpr=data
      console.log(state.formTemplate,data);

      if (state.formTemplate.templateID !== 0) {
        updateTemplate(state.formTemplate).then(response => {
          if (response.code === 0) {
            ElMessage({
              type: 'success',
              message: `修改成功`,
            })
            templateInfo();
          } else {
            ElMessage({
              type: 'error',
              message: response.msg,
            })
          }
        })
      } else {
        addTemplate(state.formTemplate).then(response => {
          if (response.code === 0) {
            ElMessage({
              type: 'success',
              message: `新增成功`,
            })
            router.push({path: '/templates/edit/'+state.formTemplate.templateCode})
          } else {
            ElMessage({
              type: 'error',
              message: response.msg,
            })
          }
        })
      }
    }
    const processingNodes = (data)=>{
      if(data.childNode&&data.type!=9){
        processingNodes(data.childNode)
      }else if(data.childNode==null&&data.type!=9){
        data['childNode']={nodeName:'流程结束',type:'9'}
      }
    }
    const saveformCss = (data)=>{
      state.formTemplate.FormCode=data
      if (state.formTemplate.templateID !== 0) {
            updateTemplate(state.formTemplate).then(response => {
              if (response.code === 0) {
                ElMessage({
                  type: 'success',
                  message: `修改成功`,
                })
                templateInfo();
              } else {
                ElMessage({
                  type: 'error',
                  message: response.msg,
                })
              }
            })
          } else {
            addTemplate(state.formTemplate).then(response => {
              if (response.code === 0) {
                ElMessage({
                  type: 'success',
                  message: `新增成功`,
                })
                router.push({path: '/templates/edit/'+state.formTemplate.templateCode})
              } else {
                ElMessage({
                  type: 'error',
                  message: response.msg,
                })
              }
            })
          }
    }
    const flowsave = (data)=>{
      let str =JSON.parse(JSON.stringify(data)) 
      processingNodes(str.nodeConfig)
      console.log(str,'dddddffffffffffffffffffffffff');
      state.formTemplate.Process=str
      if (state.formTemplate.templateID !== 0) {
            updateTemplate(state.formTemplate).then(response => {
              if (response.code === 0) {
                ElMessage({
                  type: 'success',
                  message: `修改成功`,
                })
                templateInfo();
              } else {
                ElMessage({
                  type: 'error',
                  message: response.msg,
                })
              }
            })
          } else {
            addTemplate(state.formTemplate).then(response => {
              if (response.code === 0) {
                ElMessage({
                  type: 'success',
                  message: `新增成功`,
                })
                router.push({path: '/templates/edit/'+state.formTemplate.templateCode})
              } else {
                ElMessage({
                  type: 'error',
                  message: response.msg,
                })
              }
            })
          }
    }
    return {
      Table,
      Plus,
      xxxx,
      Field,
      formEdit,
      choseTableFields,
      choseTable,
      DataGrid,
      closeDatarule,
      handleClick,
      templateInfo,
      ...toRefs(state),
      tableClick,
      normalizer,
      chosetableEvents,
      buttonsClick,
      formatterCreated,
      showReportSetForm,
      showDataGridGuid,
      changeDataType,
      submitEvent1,
      flowsave,
      processingNodes,
      saveExtFlow,
      ReportSettForm,
      toNumbers,
      getTables, getDataTypes,saveformCss,
      buildTF,
      chosetableClickEvent,
      getFieldDataGrid,
      submitEventReportSetForm,
      showpull,
      clickdefault,
      supform,
      auditoptions
    }
  }
})
</script>
<style>
.el-tabs__nav{
margin: 0px auto;
}
.my-search.vxe-input .vxe-input--suffix {
  width: 30px;
  height: 28px;
  top: 1px;
  text-align: center;
  border-left: 1px solid #dcdfe6;
  background-color: #f5f7fa;
  cursor: pointer;
  /*background: #c0c4cc !important;*/
}
.my-dropdown4 {
  width: 200px;
  height: 300px;
  background-color: #fff;
  box-shadow: 0 0 6px 2px rgba(0, 0, 0, 0.1);
}
</style>
